/*
 * File:   Clock.cpp
 * Author: joao
 *
 * Created on November 24, 2010, 5:50 PM
 */


#include "Clock.h"


Clock::Clock() {
    widget.setupUi(this);

    //disabling resizing
    this->setFixedSize(this->size());

    timer = new QTimer(this);

    //necessary initialization to avoid segfault
    music = NULL;

    connect(timer, SIGNAL(timeout()), this, SLOT(decrementMinutes()));
    connect(widget.upButton,SIGNAL(pressed()),this,SLOT(incrementMinutes()));
    connect(widget.downButton,SIGNAL(pressed()),this,SLOT(decrementMinutes()));
    connect(widget.startButton,SIGNAL(pressed()),this,SLOT(startClock()));
    connect(widget.resetButton ,SIGNAL(pressed()),this,SLOT(resetClock()));
    
}

Clock::~Clock() {
}


void Clock::incrementMinutes() {

    int currentMinutes;

    currentMinutes = widget.lcdNumberMinutes->intValue();

    widget.lcdNumberMinutes->setProperty("value", QVariant( (currentMinutes+1) % 61 ));


}

void Clock::decrementMinutes() {

    int currentMinutes;

    currentMinutes = widget.lcdNumberMinutes->intValue();

    if(widget.startButton->isEnabled() == false) {

        if(currentMinutes == 1) {
           
           widget.lcdNumberMinutes->setProperty("value", QVariant(0));
           
           music = Phonon::createPlayer(Phonon::MusicCategory,Phonon::MediaSource(":/sounds/alarm_clock.wav"));
           music->play();
           timer->stop();

        }

        else {

            widget.lcdNumberMinutes->setProperty("value", QVariant( currentMinutes-1 ));

        }

    }

    else {


       if(currentMinutes == 0)
           currentMinutes = 60;

       else
           currentMinutes = currentMinutes - 1;

       widget.lcdNumberMinutes->setProperty("value", QVariant(currentMinutes));

    }
}

void Clock::startClock() {

    int currentMinutes;

    currentMinutes = widget.lcdNumberMinutes->intValue();

    if (currentMinutes != 0) {

        timer->start(60*1000);
        widget.startButton->setEnabled(false);
        widget.upButton->setEnabled(false);
        widget.downButton->setEnabled(false);

    }

}

void Clock::resetClock() {




    timer->stop();
    
    widget.startButton->setEnabled(true);
    widget.upButton->setEnabled(true);
    widget.downButton->setEnabled(true);

    //in case the reset button is pressed in the beginning
    if(music != NULL)
    {
       music->stop();
    }
        
   

   widget.lcdNumberMinutes->setProperty("value", QVariant(0));
}